import { useI18n } from '@/hooks/web/useI18n'
import { reactive, UnwrapRef } from 'vue'
import { CrudSchema } from '@/hooks/web/useCrudSchemas'
import { useValidator } from '@/hooks/web/useValidator'
import { ActionButtonsTemplate } from '@/api/global/types'
import { useUserStore } from '@/store/modules/user'
import dayjs from 'dayjs'
import { getSalesEnumListApi } from '@/api/warehouse/merchandiseOffers'
import { getListApi as getProductListApi } from '@/api/product'

const { t } = useI18n()

const { required } = useValidator()

interface Option {
  label: string
  value: string | number // 具体取决于你的数据
}

const createOptions = (enumObject: { [key: string]: string }): Option[] => {
  return Object.keys(enumObject).map((key) => ({
    label: enumObject[key],
    value: parseInt(key, 10)
  }))
}
const userStore = useUserStore()
export default function (
  actionButtonsTemplate?: ActionButtonsTemplate,
  supplierList?: UnwrapRef<any>,
  fieldEnum?: any,
  tableDialogStoreID?: string,
  tableDialogCurdSchema?: CrudSchema[],
  operatorList?: UnwrapRef<any>,
  examine?: UnwrapRef<any>,
  detail?: UnwrapRef<any>,
  setValues?: any,
  getFormData?: any
) {
  const paytypeOption = reactive(createOptions(fieldEnum?.pay_type || {}))
  const paytermsOption = reactive(createOptions(fieldEnum?.pay_terms || {}))
  const statusOption = reactive(createOptions(fieldEnum?.status || {}))
  const paystatusOption = reactive(createOptions(fieldEnum?.pay_status || {}))
  const currencyOption = reactive(
    Object.values(fieldEnum?.currency || {}).map((item: any) => ({
      label: item.label,
      value: item.value
    }))
  )

  // is_futures 下拉选项（接口获取）
  const isFuturesOptions = reactive<Option[]>([])
  getSalesEnumListApi({ field: 'is_futures' })
    .then((resp: any) => {
      const src = resp?.data?.is_futures
      if (Array.isArray(src)) {
        isFuturesOptions.splice(
          0,
          isFuturesOptions.length,
          ...src.map((it: any) => ({ label: it.label, value: it.value }))
        )
      } else if (src && typeof src === 'object') {
        isFuturesOptions.splice(0, isFuturesOptions.length, ...createOptions(src))
      }
    })
    .catch(() => {
      // ignore fetch errors; leave options empty
    })

  const crudSchemas = reactive<CrudSchema[]>([
    {
      field: 'selection',
      search: {
        hidden: true
      },
      form: {
        hidden: true
      },
      detail: {
        hidden: true
      },
      table: {
        type: 'selection',
        selectable: (row: any) => {
          // 只有状态为 20 的行才可选
          return row.status === '20'
        }
      }
    },
    {
      field: 'id',
      label: t('purchase.id'),
      align: 'center',
      search: {
        hidden: true
      },
      form: {
        hidden: true
      },
      detail: {
        hidden: true
      },
      table: {
        headerAlign: 'center',
        align: 'center'
      }
    },
    {
      field: 'supid',
      label: t('purchase.sup'),
      search: {
        component: 'Select',
        componentProps: {
          filterable: true,
          options: supplierList
        }
      },
      form: {
        component: 'Select',
        componentProps: {
          filterable: true,
          options: supplierList,
          disabled: examine
        },
        formItemProps: {
          rules: [required()]
        }
      },
      table: {
        headerAlign: 'center',
        align: 'center',
        slots: {
          default: (data: any) => {
            return data.row.supid_value
          }
        },
        width: '120px'
      },
      detail: {
        slots: {
          default: (data: any) => {
            return data.supid_value
          }
        }
      }
    },
    {
      field: 'purchase_no',
      label: t('purchase.purchase_no'),
      search: {
        // hidden: true
      },
      form: {
        component: 'Input',
        formItemProps: {},
        componentProps: {
          disabled: examine
        }
      },
      table: {
        headerAlign: 'center',
        align: 'center',
        width: '200px'
      }
    },
    {
      field: 'is_futures',
      label: t('purchase.is_futures'),
      search: {
        component: 'Select',
        componentProps: {
          filterable: true,
          options: isFuturesOptions
        }
      },
      form: {
        hidden: true
      },
      table: {
        hidden: true
      },
      detail: {
        hidden: true
      }
    },
    {
      field: 'sales_orderno',
      label: t('purchase.sales_orderno'),
      search: {
        hidden: true
      },
      form: {
        component: 'Input',
        hidden: true,
        formItemProps: {},
        componentProps: {
          disabled: examine
        }
      },
      table: {
        hidden: true
      }
    },
    {
      field: 'purchase_goods',
      label: t('purchase.purchaseGoods'),
      table: {
        width: 460,
        align: 'center',
        headerAlign: 'center',
        slots: {
          default: ({ row }) => {
            const buyGoodsList = Array.isArray(row.purchase_goods) ? row.purchase_goods : []
            return (
              <div style={{ width: '100%', textAlign: 'center' }}>
                {buyGoodsList.map((item, index) => (
                  <div class="flex text-left" key={index}>
                    <div class="w-200 truncate" title={item?.code || ''}>
                      {item?.code || ''}
                    </div>
                    <div class="w-60">{item?.num || ''}</div>
                    <div class="w-60">{item?.subtotal || ''}</div>
                    <div class="w-120 truncate" title={item?.order_no || ''}>
                      {item?.order_no || ''}
                    </div>
                  </div>
                ))}
              </div>
            )
          }
        }
      },
      form: {
        hidden: true
      },
      search: {
        hidden: true
      }
    },
    {
      field: 'product_id',
      label: t('inventory.cname'),
      search: {
        component: 'Select',
        componentProps: {
          filterable: true,
          multiple: true,
          remote: true,
          remoteMethod: getProductOptions,
          loading: selectLoading,
          options: productList,
          placeholder: t('common.inputText') + t('inventory.cname'),
          style: {
            // width: '250px'
          }
        }
      },
      // 如果需要在表格或表单中也显示此字段，可以添加对应的配置
      table: {
        hidden: true // 可以根据需要决定是否在表格中显示
      },
      form: {
        hidden: true // 可以根据需要决定是否在表单中显示
      }
    },
    {
      field: 'type',
      label: t('purchase.purchase_type'),
      search: {
        component: 'Select',
        componentProps: {
          filterable: true,
          options: fieldEnum?.type ? reactive(createOptions(fieldEnum.type)) : []
        }
      },
      form: {
        component: 'Select',
        value: '',
        formItemProps: {},
        componentProps: {
          options: fieldEnum?.type ? reactive(createOptions(fieldEnum.type)) : [],
          disabled: examine
        }
      },
      table: {
        headerAlign: 'center',
        align: 'center',
        slots: {
          default: (data: any) => {
            const typeValue = data.row.type
            const typeOptions = fieldEnum?.type ? createOptions(fieldEnum.type) : []
            const found = typeOptions.find((item) => item.value === typeValue)
            return found ? found.label : typeValue
          }
        },
        width: '120px'
      },
      detail: {
        slots: {
          default: (data: any) => {
            return data.type_value
          }
        }
      }
    },
    {
      field: 'contract_no',
      label: t('purchase.contract_no'),
      search: {
        component: 'Input'
      },
      form: {
        component: 'Input',
        formItemProps: {},
        componentProps: {
          disabled: examine
        }
      },
      table: {
        headerAlign: 'center',
        align: 'center',
        width: '200px'
      },
      detail: {
        slots: {
          default: (data: any) => {
            return data.contract_no
          }
        }
      }
    },
    {
      field: 'order_time',
      label: t('purchase.order_time'),
      search: {
        hidden: true
      },
      form: {
        component: 'DatePicker',
        value: dayjs().format('YYYY-MM-DD'),
        formItemProps: {
          rules: [required()]
        },
        componentProps: {
          type: 'date',
          valueFormat: 'YYYY-MM-DD',
          disabled: examine
        }
      },
      table: {
        headerAlign: 'center',
        align: 'center',
        width: '200px'
      }
    },
    {
      field: 'signatoryid',
      label: t('purchase.signatory'),
      search: {
        hidden: true
      },
      form: {
        component: 'Select',
        value: userStore.getUserInfo?.id,
        formItemProps: {
          rules: [required()]
        },
        componentProps: {
          options: operatorList,
          // multiple: true,
          filterable: true,
          limit: 1,
          disabled: examine
        }
      },
      table: {
        headerAlign: 'center',
        align: 'center',
        slots: {
          default: (data: any) => {
            return data.row.signatoryid_value
          }
        }
      },
      detail: {
        slots: {
          default: (data: any) => {
            return data.signatoryid_value
          }
        }
      }
    },
    // {
    //   field: 'pay_time',
    //   label: t('purchase.pay_time'),
    //   search: {
    //     hidden: true
    //   },
    //   form: {
    //     component: 'Input',
    //     formItemProps: {},
    //     componentProps: {
    //       disabled: examine
    //     },
    //     hidden: true
    //   },
    //   table: {
    //     headerAlign: 'center',
    //     align: 'center',
    //     width: '200px'
    //   }
    // },
    {
      field: 'pay_type',
      label: t('purchase.pay_type'),
      search: {
        hidden: true
      },
      form: {
        component: 'Select',
        value: 1,
        formItemProps: {
          rules: [required()]
        },
        componentProps: {
          options: paytypeOption,
          disabled: examine
        }
      },
      table: {
        headerAlign: 'center',
        align: 'center',
        slots: {
          default: (data: any) => {
            return data.row.pay_type_value
          }
        },
        width: '120px'
      },
      detail: {
        slots: {
          default: (data: any) => {
            return data.pay_type_value
          }
        }
      }
    },
    {
      field: 'pay_terms',
      label: t('purchase.pay_terms'),
      search: {
        hidden: true
      },
      form: {
        component: 'Select',
        value: 0,
        formItemProps: {
          rules: [required()]
        },
        componentProps: {
          options: paytermsOption,
          disabled: examine
        }
      },
      table: {
        headerAlign: 'center',
        align: 'center',
        slots: {
          default: (data: any) => {
            return data.row.pay_terms_value
          }
        },
        width: '100px'
      },
      detail: {
        slots: {
          default: (data: any) => {
            return data.pay_terms_value
          }
        }
      }
    },
    {
      field: 'advance_delivery_date',
      label: t('purchase.advance_delivery_date'),
      search: {
        hidden: true
      },
      form: {
        component: 'DatePicker',
        value: dayjs().format('YYYY-MM-DD'),
        componentProps: {
          type: 'date',
          valueFormat: 'YYYY-MM-DD',
          disabled: examine
        }
      },
      table: {
        headerAlign: 'center',
        align: 'center',
        width: '200px'
      }
    },
    {
      field: 'pay_num',
      label: t('purchase.pay_num'),
      search: {
        hidden: true
      },
      form: {
        component: 'InputNumber',
        formItemProps: {},
        componentProps: {
          disabled: examine
        },
        hidden: true
      },
      table: {
        headerAlign: 'center',
        align: 'center'
      }
    },
    {
      field: 'purchase_goods',
      label: t('purchase.purchase_goods'),
      search: {
        hidden: true
      },
      form: {
        colProps: {
          span: 24
        },
        component: 'FormTable',
        formItemProps: {
          // rules: [required()]
        },
        componentProps: {
          tableDialogStoreID: tableDialogStoreID,
          tableDialogCurdSchema: tableDialogCurdSchema,
          disabled: examine,
          setValues,
          // 添加修改时的参数传递
          editMode: true,
          getCurrentFormData: getFormData || (() => ({}))
        }
      },
      table: {
        hidden: true
      }
    },
    {
      field: 'paid_amount',
      label: '已支付金额',
      search: {
        hidden: true
      },
      form: {
        hidden: !examine,
        component: 'Input',
        componentProps: {
          disabled: examine
        },
        formItemProps: {}
      },

      table: {
        headerAlign: 'center',
        align: 'center',
        width: '120px'
      }
    },
    {
      field: 'total_amount',
      label: t('purchase.total_amount'),
      search: {
        hidden: true
      },
      form: {
        hidden: !examine,
        component: 'Input',
        formItemProps: {},
        componentProps: {
          disabled: examine
        }
      },
      table: {
        headerAlign: 'center',
        align: 'center',
        width: '120px'
      }
    },
    {
      field: 'product_total_amount',
      label: t('purchase.product_total_amount'),
      search: {
        hidden: true
      },
      form: {
        component: 'Input',
        componentProps: {
          disabled: examine
        },
        formItemProps: {}
      },
      table: {
        headerAlign: 'center',
        align: 'center',
        width: '120px'
      }
    },
    {
      field: 'other_amount',
      label: t('purchase.other_amount'),
      search: {
        hidden: true
      },
      form: {
        component: 'Input',
        formItemProps: {},
        componentProps: {
          disabled: examine,
          on: {
            input: (e: string) => {
              setValues?.({ other_amount: e.replace(/^\D*(\d*(?:\.\d{0,2})?).*$/g, '$1') })
            }
          }
        }
      },
      table: {
        headerAlign: 'center',
        align: 'center',
        width: '120px'
      }
    },
    {
      field: 'notes',
      label: t('purchase.notes'),
      search: {
        hidden: true
      },
      form: {
        component: 'Input',
        formItemProps: {},
        componentProps: {
          disabled: examine
        }
      },
      table: {
        headerAlign: 'center',
        align: 'center'
      }
    },
    {
      field: 'status',
      label: t('purchase.status'),
      search: {
        component: 'Select',
        componentProps: {
          options: statusOption
        }
      },
      form: {
        hidden: true
      },
      table: {
        headerAlign: 'center',
        align: 'center',
        slots: {
          default: (data: any) => {
            return data.row.status_value
          }
        }
      }
    },
    {
      field: 'pay_status',
      label: t('purchase.pay_status'),
      search: {
        component: 'Select',
        componentProps: {
          options: paystatusOption
        }
      },
      form: {
        hidden: true
      },
      table: {
        headerAlign: 'center',
        align: 'center',
        width: '100',
        slots: {
          default: (data: any) => {
            const payStatus = data.row.pay_status
            if (payStatus === null || payStatus === undefined) {
              return ''
            }

            // 尝试数字匹配和字符串匹配
            const found = paystatusOption.find((item: any) => {
              const statusNum = parseInt(payStatus)
              return item.value === payStatus || (!isNaN(statusNum) && item.value === statusNum)
            })

            return found?.label || String(payStatus)
          }
        }
      }
    },
    {
      field: 'owner',
      label: t('purchase.owner'),
      search: {
        component: 'Select',
        componentProps: {
          options: operatorList,
          filterable: true,
          limit: 1
        }
      },
      form: {
        component: 'Select',
        formItemProps: {
          rules: [required()]
        },
        componentProps: {
          options: operatorList,
          // multiple: true,
          filterable: true,
          limit: 1,
          disabled: examine
        },
        value: userStore.getUserInfo?.id
      },
      table: {
        headerAlign: 'center',
        align: 'center',
        slots: {
          default: (data: any) => {
            return data.row.owner_value
          }
        }
      }
    },
    {
      field: 'partner',
      label: t('purchase.partner'),
      search: {
        hidden: true
      },
      form: {
        component: 'Select',
        componentProps: {
          options: operatorList,
          multiple: true,
          filterable: true,
          limit: 1,
          disabled: examine
        }
      },
      table: {
        headerAlign: 'center',
        align: 'center',
        slots: {
          default: (data: any) => {
            return data.row.partner_value
          }
        }
      }
    },
    {
      field: 'currency',
      label: t('purchase.currency'),
      search: {
        hidden: true
      },
      form: {
        component: 'Select',
        value: '',
        formItemProps: {
          rules: [required()]
        },
        componentProps: {
          options: currencyOption,
          filterable: true,
          limit: 1,
          disabled: examine
        }
      },
      table: {
        headerAlign: 'center',
        align: 'center',
        hidden: true
      }
    },
    {
      field: 'creator',
      label: t('purchase.creator'),
      search: {
        hidden: true
      },
      form: {
        hidden: true
      },
      table: {
        headerAlign: 'center',
        align: 'center',
        slots: {
          default: (data: any) => {
            return data.row.creator_value
          }
        }
      }
    },
    {
      field: 'create_time',
      label: t('purchase.create_time'),
      search: {
        hidden: true
      },
      form: {
        hidden: true
      },
      table: {
        headerAlign: 'center',
        align: 'center',
        width: '180px'
      }
    },
    {
      field: 'updater',
      label: t('purchase.updater'),
      search: {
        hidden: true
      },
      form: {
        hidden: true
      },
      table: {
        headerAlign: 'center',
        align: 'center',
        slots: {
          default: (data: any) => {
            return data.row.updater_value
          }
        }
      }
    },
    {
      field: 'update_time',
      label: t('purchase.update_time'),
      search: {
        hidden: true
      },
      form: {
        hidden: true
      },
      table: {
        headerAlign: 'center',
        align: 'center',
        width: '180px'
      }
    },

    {
      field: 'info',
      label: t('purchase.info'),
      search: {
        hidden: true
      },
      form: {
        component: 'Input',
        formItemProps: {},
        hidden: !examine,
        componentProps: {
          disabled: detail,
          type: 'textarea',
          rows: 4
        }
      },
      table: {
        hidden: true
      }
    },
    // {
    //   field: 'payments',
    //   label: t('purchase.payments'),
    //   search: {
    //     hidden: true
    //   },
    //   form: {
    //     hidden: !examine,
    //     colProps: {
    //       span: 24
    //     },
    //     component: 'PaymentTable',
    //     formItemProps: {
    //       rules: [required()]
    //     },
    //     componentProps: {
    //       disabled: examine,
    //       setValues
    //     }
    //   },
    //   table: {
    //     hidden: true
    //   }
    // },
    {
      field: 'start_date',
      label: t('common.start_time'),
      search: {
        component: 'DatePicker',
        componentProps: {
          type: 'datetime',
          valueFormat: 'YYYY-MM-DD HH:mm:ss'
        }
      },
      form: {
        hidden: true
      },
      table: {
        hidden: true
      }
    },
    {
      field: 'end_date',
      label: t('common.end_time'),
      search: {
        component: 'DatePicker',
        componentProps: {
          type: 'datetime',
          valueFormat: 'YYYY-MM-DD HH:mm:ss'
        }
      },
      form: {
        hidden: true
      },
      table: {
        hidden: true
      }
    },
    {
      field: 'action',
      width: (actionButtonsTemplate?.length || 3) * 60 + 20 + 'px',
      label: t('tableDemo.action'),
      fixed: 'right',
      search: {
        hidden: true
      },
      form: {
        hidden: true
      },
      detail: {
        hidden: true
      },
      table: {
        headerAlign: 'center',
        align: 'center',
        slots: {
          default: (data: any) => {
            return actionButtonsTemplate?.template(data) ?? null
          }
        }
      }
    }
  ])

  return {
    crudSchemas
  }
}

// 在函数开始处添加这些状态
// 产品相关状态
const productList = ref<Array<Record<string, any>>>([])
const selectLoading = ref<boolean>(false)

// 产品远程搜索方法
const getProductOptions = async (value: string) => {
  if (value) {
    selectLoading.value = true
    const productResp = await getProductListApi({ cname: value })
    productList.value = productResp.data.list?.map((item: any) => {
      return {
        label: item.cname,
        value: item.id
      }
    })
    selectLoading.value = false
  }
}
